Skip to content

Conversation

@negativ
Copy link
Contributor

@negativ negativ commented Jul 4, 2025

This change enhances the bugprone-unhandled-self-assignment checker by adding an additional matcher that generalizes the copy-and-swap idiom pattern detection.

What Changed

Added a new matcher that checks for:

  • An instance of the current class being created in operator= (regardless of constructor arguments)
  • That instance being passed to a swap function call

Problem Solved

This fix reduces false positives in PMR-like scenarios where "extended" constructors are used (typically taking an additional allocator argument). The checker now properly recognizes copy-and-swap implementations that use extended copy/move constructors instead of flagging them as unhandled self-assignment cases.

For e.g:

T& operator=(const T& other) {
   T tmp{other.internal_data(), get_allocator()};  // Extended constructor
   swap(tmp);
   return *this;
}

Fixes #146324

@github-actions
Copy link

github-actions bot commented Jul 4, 2025

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@negativ negativ marked this pull request as ready for review July 4, 2025 14:32
@llvmbot
Copy link
Member

llvmbot commented Jul 4, 2025

@llvm/pr-subscribers-clang-tidy

@llvm/pr-subscribers-clang-tools-extra

Author: Andrey Karlov (negativ)

Changes

This change enhances the bugprone-unhandled-self-assignment checker by adding an additional matcher that generalizes the copy-and-swap idiom pattern detection.

What Changed

Added a new matcher that checks for:

  • An instance of the current class being created in operator= (regardless of constructor arguments)
  • That instance being passed to a swap function call

Problem Solved

This fix reduces false positives in PMR-like scenarios where "extended" constructors are used (typically taking an additional allocator argument). The checker now properly recognizes copy-and-swap implementations that use extended copy/move constructors instead of flagging them as unhandled self-assignment cases.

For e.g:

T& operator=(const T& other) {
   T tmp{other.internal_data(), get_allocator()};  // Extended constructor
   swap(tmp);
   return *this;
}

Full diff: https://github.com/llvm/llvm-project/pull/147066.diff

2 Files Affected:

  • (modified) clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp (+18-1)
  • (modified) clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp (+90)
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
index 1f432c4ccc5f0..8307e744a434c 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
@@ -68,7 +68,23 @@ void UnhandledSelfAssignmentCheck::registerMatchers(MatchFinder *Finder) {
   const auto HasNoNestedSelfAssign =
       cxxMethodDecl(unless(hasDescendant(cxxMemberCallExpr(callee(cxxMethodDecl(
           hasName("operator="), ofClass(equalsBoundNode("class"))))))));
-
+  
+  // Checking that some kind of constructor is called and followed by a `swap`:
+  // T& operator=(const T& other) {
+  //    T tmp{this->internal_data(), some, other, args};
+  //    swap(tmp);
+  //    return *this;
+  // }
+  const auto HasCopyAndSwap = cxxMethodDecl(
+      ofClass(cxxRecordDecl(unless(hasAncestor(classTemplateDecl())))),
+      hasDescendant(
+          stmt(hasDescendant(
+                   varDecl(hasType(cxxRecordDecl(equalsBoundNode("class"))))
+                       .bind("tmp_var")),
+               hasDescendant(callExpr(callee(functionDecl(hasName("swap"))),
+                                      hasAnyArgument(declRefExpr(to(varDecl(
+                                          equalsBoundNode("tmp_var"))))))))));
+    
   DeclarationMatcher AdditionalMatcher = cxxMethodDecl();
   if (WarnOnlyIfThisHasSuspiciousField) {
     // Matcher for standard smart pointers.
@@ -94,6 +110,7 @@ void UnhandledSelfAssignmentCheck::registerMatchers(MatchFinder *Finder) {
                                    HasReferenceParam, HasNoSelfCheck,
                                    unless(HasNonTemplateSelfCopy),
                                    unless(HasTemplateSelfCopy),
+                                   unless(HasCopyAndSwap),
                                    HasNoNestedSelfAssign, AdditionalMatcher)
                          .bind("copyAssignmentOperator"),
                      this);
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
index 8610393449f97..f2f61062f883f 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
@@ -28,6 +28,13 @@ template <class T>
 class auto_ptr {
 };
 
+namespace pmr {
+    template <typename TYPE = void>
+    class allocator {};
+}
+
+struct allocator_arg_t {} allocator_arg;
+
 } // namespace std
 
 void assert(int expression){};
@@ -540,6 +547,89 @@ class NotACopyAssignmentOperator {
   Uy *getUy() const { return Ptr2; }
 };
 
+// Support "extended" copy/move constructors
+class AllocatorAwareClass {
+  // pointer member to trigger bugprone-unhandled-self-assignment
+  void *foo = nullptr;
+
+  public:
+    using allocator_type = std::pmr::allocator<>;
+
+    AllocatorAwareClass(const AllocatorAwareClass& other) {
+    }
+
+    AllocatorAwareClass(const AllocatorAwareClass& other, const allocator_type& alloc) {
+    }
+
+    AllocatorAwareClass& operator=(const AllocatorAwareClass& other) {
+        AllocatorAwareClass tmp(other, get_allocator());
+        swap(tmp);
+        return *this;
+    }
+
+    void swap(AllocatorAwareClass& other) noexcept {
+    }
+
+    allocator_type get_allocator() const {
+        return allocator_type();
+    }
+};
+
+// Support "extended" copy/move constructors + std::swap
+class AllocatorAwareClassStdSwap {
+  // pointer member to trigger bugprone-unhandled-self-assignment
+  void *foo = nullptr;
+
+  public:
+    using allocator_type = std::pmr::allocator<>;
+
+    AllocatorAwareClassStdSwap(const AllocatorAwareClassStdSwap& other) {
+    }
+
+    AllocatorAwareClassStdSwap(const AllocatorAwareClassStdSwap& other, const allocator_type& alloc) {
+    }
+
+    AllocatorAwareClassStdSwap& operator=(const AllocatorAwareClassStdSwap& other) {
+        using std::swap;
+        
+        AllocatorAwareClassStdSwap tmp(other, get_allocator());
+        swap(*this, tmp);
+        return *this;
+    }
+
+    allocator_type get_allocator() const {
+        return allocator_type();
+    }
+};
+
+// Support "extended" copy/move constructors + ADL swap
+class AllocatorAwareClassAdlSwap {
+  // pointer member to trigger bugprone-unhandled-self-assignment
+  void *foo = nullptr;
+
+  public:
+    using allocator_type = std::pmr::allocator<>;
+
+    AllocatorAwareClassAdlSwap(const AllocatorAwareClassAdlSwap& other) {
+    }
+
+    AllocatorAwareClassAdlSwap(const AllocatorAwareClassAdlSwap& other, const allocator_type& alloc) {
+    }
+
+    AllocatorAwareClassAdlSwap& operator=(const AllocatorAwareClassAdlSwap& other) {
+        AllocatorAwareClassAdlSwap tmp(other, get_allocator());
+        swap(*this, tmp);
+        return *this;
+    }
+
+    allocator_type get_allocator() const {
+        return allocator_type();
+    }
+    
+    friend void swap(AllocatorAwareClassAdlSwap&, AllocatorAwareClassAdlSwap&) {
+    }
+};
+
 ///////////////////////////////////////////////////////////////////
 /// Test cases which should be caught by the check.
 

Copy link
Contributor

@EugeneZelenko EugeneZelenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please mention changes in Release Notes.

@vbvictor vbvictor changed the title clang-tidy: Make bugprone-unhandled-self-assignment check more general [clang-tidy] Make bugprone-unhandled-self-assignment check more general Jul 4, 2025
@github-actions
Copy link

github-actions bot commented Jul 7, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

@negativ
Copy link
Contributor Author

negativ commented Jul 7, 2025

Please mention changes in Release Notes.

@EugeneZelenko done.

@MikeWeller
Copy link
Contributor

Fixes #146324

@negativ negativ requested a review from vbvictor July 21, 2025 13:57
Copy link
Contributor

@vbvictor vbvictor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@vbvictor vbvictor changed the title [clang-tidy] Make bugprone-unhandled-self-assignment check more general [clang-tidy] Make copy-and-swap idiom more general for bugprone-unhandled-self-assignment Jul 23, 2025
@vbvictor vbvictor merged commit 5de443a into llvm:main Jul 23, 2025
10 checks passed
@github-actions
Copy link

@negativ Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

mahesh-attarde pushed a commit to mahesh-attarde/llvm-project that referenced this pull request Jul 28, 2025
…ndled-self-assignment` (llvm#147066)

This change enhances the `bugprone-unhandled-self-assignment` checker by
adding an additional matcher that generalizes the copy-and-swap idiom
pattern detection.

# What Changed

Added a new matcher that checks for:
- An instance of the current class being created in operator=
(regardless of constructor arguments)
- That instance being passed to a `swap` function call

# Problem Solved
This fix reduces false positives in PMR-like scenarios where "extended"
constructors are used (typically taking an additional allocator
argument). The checker now properly recognizes copy-and-swap
implementations that use extended copy/move constructors instead of
flagging them as unhandled self-assignment cases.

Fixes llvm#146324

---------

Co-authored-by: Baranov Victor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[clang-tidy] bugprone-unhandled-self-assignment doesn't know about allocator arguments to copy/move constructors

6 participants